package navigation

import (
	"errors"
	"public_security/databases"
	"public_security/models"
	"time"
)

func Create(req *models.Navigation) error {
	req.CreateTime = time.Now().Format("2006-01-02 15:04:05")
	req.Status = 2
	if err := databases.DbDefault.Model(&models.Navigation{}).Create(req).Error; err != nil {
		return err
	}
	return nil
}

func Update(req *models.Navigation) error {
	if err := databases.DbDefault.Model(&models.Navigation{}).Where("id=?", req.Id).Updates(map[string]interface{}{"name": req.Name, "address": req.Address, "status": req.Status}).Error; err != nil {
		return err
	}
	return nil
}

func Remove(req *models.Navigation) error {
	var count int
	databases.DbDefault.Model(&models.Navigation{}).Select("count(id)").Where("id=? and status=2", req.Id).Scan(&count)
	if count > 0 {
		return errors.New("已上架的导航，不支持删除")
	}
	if err := databases.DbDefault.Model(&models.Navigation{}).Where("id=?", req.Id).Delete(req).Error; err != nil {
		return err
	}
	return nil
}

func Query(req *models.Navigation) []*models.Navigation {
	arts := make([]*models.Navigation, 0)
	db := databases.DbDefault.Model(req)
	if req.Status != 0 {
		db = db.Where("status=?", req.Status)
	}
	db.Order("create_time asc").Find(&arts)
	return arts
}
